<template>
    <div>
        <div class="informationBar" :style="styles" ref="informationBar">
            <div v-for="(v,i) in messages" :key="i">
                <span class="name" v-if="v.name">{{v.name}}：</span>
                <p class="speak">{{v.text}}</p>
            </div>
        </div>
    </div>
</template>

<script>
    const other_height=450;
    export default {
        name: "SocketInformationBar",
        props: {
            socket: {
                type: Object,
                default: ()=>null
            }
        },
        data(){
            return {
                messages: [],
                styles: {
                    maxHeight: (window.innerHeight-other_height)+'px',
                    overflowY: "auto",

                }
            }
        },
        watch:{
            socket: function(new_socket){
                if(new_socket){
                    new_socket.on('get_message', (msg)=>{
                        this.$data.messages.push(msg);
                        this.to_bottom();
                    });
                    new_socket.on('message', (msg)=>{
                        this.$data.messages.push(msg);
                        this.to_bottom();
                    });
                }
            },
            messages: function(n){
                if(n.length>50){
                    this.$data.messages.shift();
                }
            }
        },
        methods: {
            change_size(){  //动态设置消息框的高度
                var in_height= window.innerHeight;
                if(window.innerHeight<100){
                    in_height=100
                }
                this.$data.styles.maxHeight= (in_height-other_height)+'px';

            },
            to_bottom(){  //聊天记录块置底
                setTimeout(()=>{
                    this.$refs.informationBar.scrollTop= this.$refs.informationBar.offsetHeight;
                },300)

            }
        },
        mounted(){
            window.onresize=this.change_size;
        }
    }
</script>

<style scoped>
    .informationBar{
        margin: auto;
        max-width: 400px;
        text-align: left;
    }
    .speak{
        margin: 6px;
        background: #32a8e6;
        color: #fff;

        display: inline-block;
        font-size: 14px;
        max-width: 90%;
        padding: 8px 14px;
        border-radius: 18px;
        min-width: 0;
    }
</style>
